package com.xiaolin.springbootdemo.exception;

import com.xiaolin.springbootdemo.utils.ResponseResult;
import com.xiaolin.springbootdemo.utils.ResultCode;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常处理器
 * @Detail detail
 * @Author MyPC
 * @Date 2021/1/10
 * @Version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 自定义请求处理异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(RequestHandleException.class)
    public ResponseResult handle(RequestHandleException e){
        if(e.getICommonCode()!=null){
            return ResponseResult.error(e.getICommonCode());
        }
        return ResponseResult.error(e.getMessage());
    }

    /**
     * 数字处理异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ArithmeticException.class)
    public ResponseResult handleArithmeticException(ArithmeticException e){
        return ResponseResult.error(ResultCode.NUMBER_HANDLE_ERROR.getMsg()+",原因："+e.getMessage());
    }

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ResponseResult handleBindException(BindException e){
        BindingResult bindingResult = e.getBindingResult();
        String errorMsg="";
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if(fieldErrors.size() >0){
            List<String> errors=fieldErrors.stream().map(item -> {
                return "{ 异常参数："+item.getField()+"，"+"出错原因："+item.getDefaultMessage()+" }";
            }).collect(Collectors.toList());
            errorMsg=errors.toString();
        }
        return ResponseResult.error(errorMsg);
    }
}
